package com.example.demo.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

@Component
public class FileUtils {
	@Value("${file.upload.path}")
	private String uploadPath;

	public boolean uploadFile(MultipartFile file, String filename){
		if (file.isEmpty()) { return false;}
        File uploadFile = new File(filename);
        try {
            file.transferTo(uploadFile);
            return true;
        } catch (IOException e) {
            System.out.print(e.toString());
        }
        return false;
	}
	public String getClassPath() {
        try {
            return ResourceUtils.getURL("classpath:").getPath();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
	public String getUploadPath() {
		File file = new File(getClassPath(), uploadPath);
		if(!file.exists()){
			boolean b = file.mkdir();
		}
		return file.getAbsolutePath();
	}
//	public String getUploadPath(){
//		String projectPath = System.getProperty("user.dir").replace('\\','/');
//		return projectPath + "/" + uploadPath;
//	}
	public String getUploadPath(String childPath){
		File file = new File(getUploadPath(), childPath);
		if(!file.exists()){
			boolean b = file.mkdir();
		}
		return file.getAbsolutePath();
	}
	public String getFileNameTrimExt(String filename) {
        if ((filename != null) && (!filename.isEmpty())) {
            int dot = filename.lastIndexOf('.'); 
            if (dot > 0) {
                return filename.substring(0, dot); 
            } 
        } 
        return filename; 
    }
	public String getExtensionName(String filename) {
		if ((filename != null) && (!filename.isEmpty())) {
			int dot = filename.lastIndexOf('.');
			if ((dot > 0) && (dot < (filename.length() - 1))) {
				return filename.substring(dot + 1);
			}
		}
		return filename;
	}
	public String getFileNameByTime(String fileName) {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmssSSS");
		return format.format(new Date()) + new Random().nextInt(1000) + "." + getExtensionName(fileName);
	}
}